package simonby.top.annualring.adapter.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import simonby.top.annualring.application.service.UserApplicationService;
import simonby.top.annualring.application.service.PermissionApplicationService;
import simonby.top.annualring.domain.model.User;
import simonby.top.annualring.adapter.dto.UserDTO;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户控制器
 * 处理用户相关的HTTP请求
 */
@RestController
@RequestMapping("/api/users")
public class UserController {
    private final UserApplicationService userApplicationService;
    private final PermissionApplicationService permissionApplicationService;

    public UserController(UserApplicationService userApplicationService,
                         PermissionApplicationService permissionApplicationService) {
        this.userApplicationService = userApplicationService;
        this.permissionApplicationService = permissionApplicationService;
    }

    /**
     * 创建用户（仅管理员可以创建用户）
     * @param userDTO 用户DTO
     * @return 创建后的用户DTO
     */
    @PostMapping
    public SaResult createUser(@RequestBody UserDTO userDTO) {
        // 检查是否为系统管理员
        if (!permissionApplicationService.isSystemAdmin()) {
            return SaResult.error("无权限创建用户");
        }
        
        User user = convertToDomain(userDTO);
        User savedUser = userApplicationService.createUser(user);
        return SaResult.ok("创建成功").setData(convertToDTO(savedUser));
    }

    /**
     * 根据ID获取用户
     * @param id 用户ID
     * @return 用户DTO
     */
    @GetMapping("/{id}")
    public SaResult getUserById(@PathVariable Long id) {
        // 用户只能查看自己的信息，管理员可以查看所有用户
        if (!Objects.equals(StpUtil.getLoginIdAsLong(), id) && !permissionApplicationService.isSystemAdmin()) {
            return SaResult.error("无权限查看该用户信息");
        }
        
        return userApplicationService.getUserById(id)
                .map(user -> SaResult.data(convertToDTO(user)))
                .orElse(SaResult.error("用户不存在"));
    }

    /**
     * 获取所有用户（仅管理员可以获取）
     * @return 用户DTO列表
     */
    @GetMapping
    public SaResult getAllUsers() {
        // 检查是否为系统管理员
        if (!permissionApplicationService.isSystemAdmin()) {
            // 对于非管理员用户，返回权限错误
            return SaResult.error("无权限获取用户列表");
        }
        
        List<UserDTO> users = userApplicationService.getAllUsers().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
        return SaResult.data(users);
    }

    /**
     * 更新用户
     * @param id 用户ID
     * @param userDTO 用户DTO
     * @return 更新后的用户DTO
     */
    @PutMapping("/{id}")
    public SaResult updateUser(@PathVariable Long id, @RequestBody UserDTO userDTO) {
        // 用户只能更新自己的信息，但不能更新角色和状态，管理员可以更新所有信息
        Long currentUserId = StpUtil.getLoginIdAsLong();
        boolean isSystemAdmin = permissionApplicationService.isSystemAdmin();
        
        if (!Objects.equals(currentUserId, id) && !isSystemAdmin) {
            return SaResult.error("无权限更新该用户信息");
        }
        
        // 非管理员不能更新角色和状态
        if (!isSystemAdmin) {
            User originalUser = userApplicationService.getUserById(id).orElse(null);
            if (originalUser != null) {
                userDTO.setRole(originalUser.getRole());
                userDTO.setStatus(originalUser.getStatus());
            }
        }
        
        userDTO.setId(id);
        User user = convertToDomain(userDTO);
        User updatedUser = userApplicationService.updateUser(user);
        return SaResult.ok("更新成功").setData(convertToDTO(updatedUser));
    }

    /**
     * 删除用户（仅管理员可以删除用户）
     * @param id 用户ID
     */
    @DeleteMapping("/{id}")
    public SaResult deleteUser(@PathVariable Long id) {
        // 检查是否为系统管理员
        if (!permissionApplicationService.isSystemAdmin()) {
            return SaResult.error("无权限删除用户");
        }
        
        // 不能删除自己
        if (Objects.equals(StpUtil.getLoginIdAsLong(), id)) {
            return SaResult.error("不能删除当前登录用户");
        }
        
        userApplicationService.deleteUser(id);
        return SaResult.ok("删除成功");
    }

    /**
     * 将UserDTO转换为User领域对象
     * @param userDTO 用户DTO
     * @return User领域对象
     */
    private User convertToDomain(UserDTO userDTO) {
        User user = new User();
        user.setId(userDTO.getId());
        user.setUsername(userDTO.getUsername());
        user.setPassword(userDTO.getPassword());
        user.setNickname(userDTO.getNickname());
        user.setEmail(userDTO.getEmail());
        user.setPhone(userDTO.getPhone());
        user.setAvatar(userDTO.getAvatar());
        user.setStatus(userDTO.getStatus());
        user.setRole(userDTO.getRole());
        user.setCreateTime(userDTO.getCreateTime());
        user.setUpdateTime(userDTO.getUpdateTime());
        user.setLastLoginTime(userDTO.getLastLoginTime());
        return user;
    }

    /**
     * 将User领域对象转换为UserDTO
     * @param user User领域对象
     * @return 用户DTO
     */
    private UserDTO convertToDTO(User user) {
        UserDTO userDTO = new UserDTO();
        userDTO.setId(user.getId());
        userDTO.setUsername(user.getUsername());
        userDTO.setPassword(user.getPassword());
        userDTO.setNickname(user.getNickname());
        userDTO.setEmail(user.getEmail());
        userDTO.setPhone(user.getPhone());
        userDTO.setAvatar(user.getAvatar());
        userDTO.setStatus(user.getStatus());
        userDTO.setRole(user.getRole());
        userDTO.setCreateTime(user.getCreateTime());
        userDTO.setUpdateTime(user.getUpdateTime());
        userDTO.setLastLoginTime(user.getLastLoginTime());
        return userDTO;
    }
}